import * as vscode from 'vscode';
import { SnippetManager } from '../utils/snippetManager';
import { SnippetProvider } from '../providers/snippetProvider';

export class DeleteSnippetCommand {
    constructor(
        private snippetManager: SnippetManager,
        private snippetProvider: SnippetProvider
    ) {}

    get commandId(): string {
        return 'snippetManager.deleteSnippet';
    }

    async execute(item?: any): Promise<void> {
        try {
            let snippet = item?.snippet;
            if (!snippet) {
                // 如果没有提供snippet，让用户选择
                const snippets = this.snippetManager.getAllSnippets();
                if (snippets.length === 0) {
                    vscode.window.showInformationMessage('No snippets to delete');
                    return;
                }

                const items = snippets.map(s => ({
                    label: s.name,
                    description: `${s.group} • ${s.description}`,
                    snippet: s
                }));

                const selected = await vscode.window.showQuickPick(items, {
                    placeHolder: 'Select a snippet to delete...'
                });

                if (!selected) return;
                snippet = selected.snippet;
            }

            // 确认删除
            const confirm = await vscode.window.showWarningMessage(
                `Are you sure you want to delete snippet "${snippet.name}"?`,
                'Delete',
                'Cancel'
            );

            if (confirm !== 'Delete') return;

            // 删除代码片段
            const success = await this.snippetManager.deleteSnippet(snippet.id);
            if (success) {
                this.snippetProvider.refresh();
                vscode.window.showInformationMessage(`Snippet "${snippet.name}" deleted successfully!`);
            } else {
                vscode.window.showErrorMessage('Failed to delete snippet');
            }

        } catch (error) {
            vscode.window.showErrorMessage(`Failed to delete snippet: ${error}`);
        }
    }
}
